/*
 Simple MPI-IO program that demonstrate parallel reading from a file.
 Compile the program with 'mpicc -O2 readfile1.c -o readfile1'

 Check if the number of elements read per process is correct !!!
 */

/*Slide 41 in  Introduction to Parallel I/O
 * Best practices slides 50-52
 *
 * Jumpshot and MPE tools
 * http://www.mcs.anl.gov/perfvis
 TAU
 * http://www.cs.uoregon.edu/research/tau/home.php
 Intel Trace Analyzer and Collector (formerly Pallas Vampir)
 * http://www.intel.com/cd/software/products/asmo-na/eng/cluster/tanalyzer/index.htm
 Paradyn
 * http://www.cs.wisc.edu/~paradyn
 Pablo
 * http://www.renci.org/software/
 Many other vendor tools exist
 * e.g., xmpi (SGI and HP)
 *
 * Reads file using MPI_File_read with fixed sized buffer
 * */
#include <stdlib.h>
#include <stdio.h>
#include "mpi.h"

int main(int argc, char* argv[]) {
	int np, myid;
	MPI_Offset offset;
	MPI_File myfile; /* Shared file */
	MPI_Status status; /* Status returned from read */

	/* Initialize MPI */
	MPI_Init(&argc, &argv);
	MPI_Comm_rank(MPI_COMM_WORLD, &myid);
	MPI_Comm_size(MPI_COMM_WORLD, &np);

	/* Open the file */
	MPI_File_open(MPI_COMM_WORLD, "mmapped512gb.bin", MPI_MODE_RDONLY,
			MPI_INFO_NULL, &myfile);

	int * buf= (int*) malloc(1024 * sizeof(int));;
	for (int i = 0; i <  131072; i++)  {
		MPI_File_read_at(myfile, i * 1024, buf, 1024, MPI_INT,
				&status);
	}

	/* Close the file */

	delete[] buf;
	MPI_File_close(&myfile);
	MPI_Finalize();
	exit(0);

}

/*
 Get the size of the file
 MPI_File_get_size(myfile, &filesize);
 Calculate how many elements that is
 filesize = filesize / sizeof(char);
 Calculate how many elements each processor gets
 //bufsize = filesize/np;
 bufsize = filesize;
 Allocate the buffer to read to, one extra for terminating null char
 buf = (char *) malloc((bufsize + 1) * sizeof(char));
 Set the file view
 MPI_File_set_view(myfile, 0 * bufsize * sizeof(char), MPI_CHAR, MPI_BYTE,
 "native", MPI_INFO_NULL);
 Read from the file
 MPI_File_read(myfile, buf, bufsize, MPI_CHAR, &status);
 Find out how many elemyidnts were read

 MPI_Get_count(&status, MPI_BYTE, &nrchar);
 Set terminating null char in the string
 buf[nrchar] = (char) 0;
 printf("Process %2d read %d characters: ", myid, nrchar);
 printf("  %s\n", buf);
 */

